
let fs=require('fs');
let path=require('path');
let router=require('koa-router')();



function createControllers(defaultDir) {

    let files=fs.readdirSync(defaultDir);

    let resultFiles=files.filter((fileName)=>{
        return fileName.endsWith('.js') && fileName !=='index.js';
    });
    return resultFiles;
}


function createEachFile(files) {
    files.forEach(ele=>{
        let tmpFile = require(path.join(__dirname,ele));
        for(let key in tmpFile){
            let type = tmpFile[key][0];
            let value = tmpFile[key][1];

            if(type === 'get'){
                router.get(key,value);
            }else if(type === 'post'){
                router.post(key,value);
            }
        }
    })
}


module.exports=function (dir) {
    let defaultDir=dir || '/controllers'
    
    let root=path.resolve('.');
    
    let c=path.join(root,defaultDir);

    let files=createControllers(c);

    createEachFile(files,c);

    return router.routes();
}